package com.jd.sunny.java.collection;

import java.util.Comparator;
import java.util.PriorityQueue;

/**
 * @Description:PriorityQueue,is not thread safe,we can use PriorityBlockingQueue in  multithreading
 * @author:sunlin
 * @since:2012-12-06 10:33
 * @version:1.0.0
 */

/**
 * 1.is not thread safe,we can use PriorityBlockingQueue in  multithreading
 * 2.it is  auto increment, capacity infinite
 * 3.we can not add null element
 * 4.use  Arrays.sort(pq.toArray()) to traverse the queue ,but we can not use iterator because it do not have order
 */
public class TestPriorityQueue {

    public static void main(String[]args){
        // new a PriorityQueue object ,PriorityQueue is a generic class
        //first parameter is capacity,second parameter is a Comparator object
        //PriorityQueue can  increase autoly;
        PriorityQueue<Item> priorityQueue = new PriorityQueue<Item>(15,new Comparator<Item>() {
            public int compare(Item o1, Item o2) {
//                return o1.getName().compareTo(o2.getName());
                return o1.getPriority()-o2.getPriority();
            }
        });

        Item i1 = new Item();
        i1.setName("System Manager");
        i1.setPriority(1);

        Item i2 = new Item();
        i2.setName("System Config");
        i2.setPriority(2);

        Item i3 = new Item();
        i3.setName("User Config");
        i3.setPriority(3);

        Item i4 = new Item();
        i4.setName("User Manager");
        i4.setPriority(4);

        //add elements without sort,use offer method ,if add failed will return false
        // we can not add null 
        priorityQueue.offer(i2);
        priorityQueue.offer(i1);
        priorityQueue.offer(i4);
        priorityQueue.offer(i3);

        //only get first element but not delete,if the priority queue is null,return null
        //the order is sorted by the Comparator object
        Item firstItem =  priorityQueue.peek();

        //get and delete first element, if the priority queue is null,return null
        Item firstItem1 = priorityQueue.poll();

        //AbstractQueue method,it call the poll method,so it is the same as poll
        /**
         E x = poll();
         if (x != null)
         return x;
         else
         throw new NoSuchElementException();
         */
        Item firstItem2 = priorityQueue.remove();

        System.out.println(firstItem.toString());
        System.out.println(firstItem1.toString());
        System.out.println(firstItem2.toString());

    }
}
